<template>
    <div>
        <div v-if="devEnv" @click="$emit('success')">success</div>
        <div v-if="devEnv" @click="$emit('fail', '失败')">fail</div>
        <div class="sketch">
            <div class="sketch-img"></div>
            <p class="sketch-text">正面平视手机、保证光线充足<br />请勿遮挡面部</p>
        </div>
        <div class="prompt">
            <div class="prompt-box">
                <div class="prompt-box-text" v-for="item in items" :key="item.number">
                    <span class="prompt-box-text-number">{{item.number}}</span><span
                        class="prompt-box-text-content">{{item.text}}</span>
                    <span class="prompt-box-text-border" v-if="item.border"></span>
                </div>
            </div>
            <span class="prompt-next" :class="{'prompt-next-disabled': nextDisabled}" @click="nextStep">下一步</span>
        </div>

        <div id="in-box" style="display:none"></div>

        <popupError v-if="showPopupError" :showPopupError.sync="showPopupError" />
        <verifyCodeModal v-if="showVerifyCodeModal" @cancel="onDialogCancel" @videoResult="onDialogVideoResult"
            :videoFail.sync="videoFail" :videoFailText.sync="videoFailText" />
        <loading v-if="showLoading"></loading>
        <result v-if="showResult" @restart="onDialogAgain" :showResult.sync="showResult"
            :videoResultDetail="videoResultDetail"></result>
    </div>
</template>

<script>
    /**
     * @file 人脸活体检测h5 demo容器组件
     * @author v_yangbin02
     */

    import request from 'superagent';
    import verifyCodeModal from '../components/verifyCodeModal';
    import loading from '../components/loading';
    import result from '../components/result';
    import popupError from '../components/popupError';
    const FILE_SIZE = 256 * 1024;
    const IMAGE_MAX_PIXEL = 500000;

    export default {
        components: {
            verifyCodeModal,
            loading,
            result,
            popupError
        },
        data() {
            return {
                devEnv: process.env == 'development',
                showVerifyCodeModal: false,
                verifyCode: '',
                nextDisabled: false,
                showLoading: false,
                showResult: false,
                videoResultDetail: null,
                videoFail: false,
                videoFailText: {},
                showPopupError: false,
                items: [{
                    number: 1,
                    text: '记住提示的指令，点击开始录制',
                    border: 1
                }, {
                    number: 2,
                    text: '开启前置摄像头，做相应的指令动作',
                    border: 1
                }, {
                    number: 3,
                    text: '完成录制，等待验证结果',
                    border: 0
                }]
            };
        },

        mounted() {
            this.$util.speckText('请阅读相关说明和步骤，点击下一步开始资格认证。', 'zgrz');
        },

        methods: {
            onDialogCancel() {
                this.nextDisabled = false;
                this.showVerifyCodeModal = false;
            },

            onDialogAgain() {
                this.nextDisabled = false;
                this.showResult = false;
                this.showVerifyCodeModal = true;
            },

            onDialogVideoResult(event, sessionId) {
                // 显示loding图
                var $ = window.$;
                const files = event.target.files;
                this.showLoading = true;

                if (files && files.length > 0) {
                    let file = files[0];
                    let self = this;
                    if (file.size > 50 * 1024 * 1024) {
                        this.showLoading = false;
                        this.videoFail = true;
                        this.videoFailText = {
                            title: '视频上传失败',
                            detail: '您录制的视频时间过大,请重新录制'
                        };
                        return;
                    }

                    var blob = new Blob([file]), // 文件转化成二进制文件
                        url = URL.createObjectURL(blob); //转化成url

                    var oVideo = '';
                    var isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || navigator.userAgent
                        .includes('Safari');
                    var oInBox = document.getElementById('in-box');

                    if (isIOS) {
                        var dom = $(`
                        <video id="oVideo" x5-video-player-type="h5" width="100%" loop="loop" 
                            webkit-playsinline="true" playsinline="true"
                            autoplay controls style="position: absolute;top: -1000px">
                        　　<source id="oVideoSrc" type="video/mp4" -webkit-playsinline="true"  src="">
                        </video>`);
                        oVideo = dom[0];
                        var oVideoSrc = dom.find('#oVideoSrc');
                        oVideoSrc.attr('src', url);
                        oVideo.currentTime = 2;
                        oInBox.appendChild(oVideo);
                    } else {
                        // 安卓
                        oVideo = document.createElement('video');
                        oVideo.setAttribute('src', url);
                        oVideo.setAttribute('controls', 'controls');
                        oVideo.currentTime = 2; // 设置当前视频为 第1s
                        oInBox.appendChild(oVideo);
                    }

                    oVideo.addEventListener('canplay', function () {
                        var oCanvas = document.createElement('canvas');
                        oCanvas.width = oVideo.videoWidth;
                        oCanvas.height = oVideo.videoHeight;
                        oCanvas.getContext("2d").drawImage(oVideo, 0, 0, oCanvas.width, oCanvas.height);

                        var base64 = oCanvas.toDataURL("image/png");
                        new Promise(resolve => {
                            let imgSize = base64.length;
                            if (imgSize <= FILE_SIZE) {
                                resolve(base64);
                            } else {
                                console.log('压缩前大小:' + imgSize);
                                let img = new Image();
                                img.src = base64;
                                img.onload = function () {
                                    let data = self.compress(img, "", "image/png", 1048576 /
                                        imgSize);
                                    console.log('压缩后大小:' + data.length);
                                    resolve(data);
                                };
                            }
                        }).then((base64Zip => {
                            let formdata = {
                                cardId: '320281199606286774',
                                'image_base64': base64Zip.split(',')[1]
                            };

                            request
                                .post('api/compareinfo6.jsp')
                                .type('form')
                                .send(formdata)
                                .then(({
                                    body
                                }) => {
                                    if (body.success) {
                                        // 通过
                                        self.$emit('success');
                                        return;
                                    } else {
                                        self.$emit('fail', body.msg);
                                    }
                                })
                                .catch(msg => {
                                    self.errorContent();
                                });
                        }));

                    });


                    isIOS && setTimeout(() => {
                        oVideo.play();
                    }, 500);
                }
            },
            compress(img, Orientation, fileType, rate) {
          let canvas = document.createElement("canvas");
          let ctx = canvas.getContext("2d");
          let tCanvas = document.createElement("canvas");
          let tctx = tCanvas.getContext("2d");
          let initSize = img.src.length;
          let width = img.width;
          let height = img.height;
          // 如果图片大于XXX像素，计算压缩比并将大小压至XXX以下
          let ratio;
          if ((ratio = width * height / IMAGE_MAX_PIXEL) > 1) {
            console.log("大于"+IMAGE_MAX_PIXEL+"像素");
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
          } else {
            ratio = 1;
          }
          canvas.width = width;
          canvas.height = height;
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          // 如果图片像素大于XXX2则使用瓦片绘制
          let count;
          if ((count = width * height / IMAGE_MAX_PIXEL) > 1) {
            console.log("超过"+IMAGE_MAX_PIXEL+"像素");
            count = ~~(Math.sqrt(count) + 1);
            let nw = ~~(width / count);
            let nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (let i = 0; i < count; i++) {
              for (let j = 0; j < count; j++) {
                tctx.drawImage(
                  img,
                  i * nw * ratio,
                  j * nh * ratio,
                  nw * ratio,
                  nh * ratio,
                  0,
                  0,
                  nw,
                  nh
                );
                ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
              }
            }
          } else {
            ctx.drawImage(img, 0, 0, width, height);
          }
          let ndata = canvas.toDataURL(fileType, rate);
          console.log("压缩前：" + initSize);
          console.log("压缩后：" + ndata.length);
          console.log(
            "压缩率：" + ~~(100 * (initSize - ndata.length) / initSize) + "%"
          );
          tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
          return ndata;
        },
            nextStep() {
                this.showVerifyCodeModal = true;
            },

            errorContent(t1, t2) {
                this.showLoading = false;
                this.videoFail = true;
                this.$util.speckText('认证失败，请重试', 'fail-r');
                this.videoFailText = {
                    title: t1 || '视频上传失败',
                    detail: t2 || '视频上传失败，请重新上传'
                };
            }
        }
    };
</script>
<style lang="less">
    @color-blue: #0073eb;

    html,
    body {
        height: 100%;
        margin: 0;
        font-size: 12px;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        overflow: hidden;
        font-family: tahoma, arial, "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
    }

    * {
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }

    @media (max-width: 374px) {

        html,
        body {
            font-size: 9px;
        }
    }

    .sketch {
        background: rgba(225, 225, 225, .35);
        padding: 0.5rem 1.666rem 0.5rem;

        &-img {
            width: 14.916rem;
            height: 21.583rem;
            margin: 0 auto;
            background: url(../../../images/sketch.png) 0 0 no-repeat;
            // background-size: 100% auto;

            max-width: 120px;
            max-height: 150px;
            background-size: 100% 100%;
        }

        &-text {
            font-size: 14px;
            color: #999;
            letter-spacing: 0;
            line-height: 24px;
            text-align: center;
        }
    }

    .prompt {
        box-shadow: 0 -4px 10px 0 #e8e8e8;
        padding-bottom: 0.833rem;

        &-box {
            padding: 4.166rem 0;

            &-text {
                margin: 0 auto 2.666rem;
                height: 1.334rem;
                line-height: 1.334rem;
                width: 25.5rem;

                &:last-child {
                    margin-bottom: 0;
                }

                &-number {
                    border-radius: 200px;
                    border: 1px solid @color-blue;
                    text-align: center;
                    color: @color-blue;
                    display: inline-block;
                    width: 1.334rem;
                    height: 1.333rem;
                    line-height: 1.333rem;
                    box-sizing: border-box;
                    font-size: 12px;
                    margin-right: .833rem;
                    letter-spacing: 0;
                    vertical-align: top;
                }

                &-content {
                    color: #333;
                    letter-spacing: 0;
                    white-space: nowrap;
                    display: inline-block;
                    font-size: 1.333rem;
                }

                &-border {
                    height: 1.9rem;
                    margin: .417rem 0 .417rem 0.59rem;
                    width: 0;
                    border-left: 1px dotted @color-blue;
                    display: block;
                }
            }
        }

        &-next {
            margin: 0 auto;
            height: 4.083rem;
            line-height: 4.083rem;
            text-align: center;
            background: @color-blue;
            border-radius: 4px;
            color: #fff;
            display: block;
            width: 28.75rem;
            font-size: 16px;
            outline: none;
            border: none;
            max-width: 90%;

            &-disabled {
                background-color: #ccc;
            }
        }
    }
</style>